import pymysql
from common.config import *
from itertools import chain


class MysqlDb():
    def __init__(self, env):
        host_db = getconf(env, "host_db")
        user_db = getconf(env, "user_db")
        password = getconf(env, "password")
        port_db = getconf(env, "port")
        name_db = getconf(env, "name_db")
        try:
            self.db = pymysql.connect(host=host_db, port=int(port_db), user=user_db, password=password, db=name_db,
                                      charset="utf8")  # 链接数据库
            self.cursor = self.db.cursor()  # 获取操作游标
            # print("数据库连接成功")
        except pymysql.Error as e:
            print("数据库连接失败|Mysql Error %d:%s" % (e.args[0], e.args[1]))

    def mysql_db(self,sql_connect):

        """操作Mysql数据库"""
        # db = pymysql.connect(host=mysql_host, port=int(mysql_port),
        #                      user=mysql_user, passwd=mysql_password,
        #                      db=mysql_db_name)

        # cursor = db.cursor()  # 获取操作游标
        # 获取组-id
        sql = sql_connect
        self.cursor.execute(sql)
        version = self.cursor.fetchall()
        # version = list(chain.from_iterable(version))  # 定位方式  二维元组转换为一维列表
        # pprint.pprint(version,indent=2)
        self.db.commit()
        self.cursor.close()  # 关闭游标
        self.db.close()  # 关闭数据库
        return version
